package com.example.estest.util;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import java.io.File;
import java.net.InetAddress;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ip地址解析，通过geoip地理库
 */
public class IpUtil {
    public static LinkedHashMap<String, Object> ipUtil(String ipAddress) {
        try {
            // 换成自己的 MaxMind GeoIP2 数据库文件路径
            File database = new File("src/main/resources/GeoLite2-City.mmdb");

            // 初始化 GeoIP2 DatabaseReader
            DatabaseReader reader = new DatabaseReader.Builder(database).build();

            // 进行IP地址查询
            InetAddress ip = InetAddress.getByName(ipAddress);
            CityResponse response = reader.city(ip);

            // 获取地理信息
            City city = response.getCity();
            String city_name = city.getNames().get("zh-CN");    //中文
            String region_name = response.getMostSpecificSubdivision().getNames().get("zh-CN");
            Double latitude = response.getLocation().getLatitude();
            Double longitude = response.getLocation().getLongitude();
            String country_name = response.getCountry().getNames().get("zh-CN");
            LinkedHashMap<String, Object> geoip = new LinkedHashMap<>();

            geoip.put("city_name",city_name);
            geoip.put("region_name",region_name);
            geoip.put("latitude",latitude);
            geoip.put("ip",ipAddress);
            geoip.put("longitude",longitude);
            geoip.put("country_name",country_name);
            if(geoip.get("region_name") == null) {
                geoip.put("region_name",geoip.get("country_name"));
            }
            if(geoip.get("city_name") == null) {
                geoip.put("city_name",geoip.get("country_name"));
            }
            return geoip;
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

    public static LinkedHashMap<String, Object> NotIsIpUtil(String ipAddress) {
        LinkedHashMap<String, Object> geoip = new LinkedHashMap<>();
        geoip.put("city_name","内网");
        geoip.put("country_name","内网");
        geoip.put("region_name","内网");
        geoip.put("ip",ipAddress);
        return geoip;
    }
}
